% gossipprob.erl
%
% Given a neighbor list, uses the probability distribution to randomly pick a neighbor
% and returns the neighbor
%
-module(gossipprob).
-export([getGossipNode/1]).
-import(erlang, [display/1]).

-export([getGossipNode_help/4]).

getGossipNode(Neighbors) ->
  random:seed(now()),
  Random = random:uniform(),
  getGossipNode_help(Neighbors, Neighbors, Random, 0).

getGossipNode_help([], _Neighbors, _Random, _Add) ->
  {error, endoflist};
getGossipNode_help(LeftToCheck, Neighbors, Random, Add) ->
  HeadNodeProb = getProbability(Neighbors, hd(LeftToCheck)),
  if
    (Add =< Random) and (Add + HeadNodeProb > Random) ->
      
      {ok, hd(LeftToCheck)};
    true ->
      getGossipNode_help(
          tl(LeftToCheck),
          Neighbors,
          Random,
          Add + HeadNodeProb)
  end.

getProbability(MyNeighbors, Neighbor) ->
	Neighbor ! {sizeN, self()},
	NumNRndmNode = popMessage(),
	MyNumNodes = length(MyNeighbors),
	1.0 / (1.0 + erlang:max(MyNumNodes, NumNRndmNode)).

popMessage() ->
	receive
		Msg -> Msg
	end.
